package com.shortchina.common.util;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname test
 * @Date 2025/1/21 15:03
 * @Created by 87766867@qq.com
 */
public class test {
    // Base62字符集
    private static final String BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // 模拟数据库表，存储长URL到随机ID的映射
    private static final ConcurrentHashMap<String, BigInteger> urlToIdMap = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<BigInteger, String> idToUrlMap = new ConcurrentHashMap<>();

    // 安全随机数生成器
    private static final SecureRandom secureRandom = new SecureRandom();

    // 生成指定位数的随机BigInteger
    private static BigInteger generateRandomId(int bitLength) {
        return new BigInteger(bitLength, secureRandom);
    }

    // 将长URL转为6位的短链接码
    public static String generateShortUrl(String longUrl) {
        // 如果已经存在对应的短链，则直接返回已有的短链
        if (urlToIdMap.containsKey(longUrl)) {
            return encode(urlToIdMap.get(longUrl)).substring(0, 6);
        }

        BigInteger id;
        String shortCode;
        do {
            id = generateRandomId(24); // 例如24位的随机数以保证足够大的随机空间
            shortCode = encode(id);
            // 确保短链至少有5个字符，不够则用'0'填充
            while (shortCode.length() < 6) {
                shortCode = '0' + shortCode;
            }
            shortCode = shortCode.substring(0, 6); // 取前6位作为短链
        } while (idToUrlMap.containsKey(decode(shortCode)));

        // 插入新的映射关系
        urlToIdMap.put(longUrl, id);
        idToUrlMap.put(decode(shortCode), longUrl);

        return shortCode;
    }

    // 解码短链接码为原始URL
    public static String resolveShortUrl(String shortCode) {
        return idToUrlMap.get(decode(shortCode)); // 使用idToUrlMap来查找对应的长URL
    }

    // 将随机ID转换为Base62编码的短链
    private static String encode(BigInteger id) {
        StringBuilder shortUrlBuilder = new StringBuilder();
        while (id.compareTo(BigInteger.ZERO) > 0) {
            shortUrlBuilder.append(BASE62.charAt(id.mod(BigInteger.valueOf(62)).intValue()));
            id = id.divide(BigInteger.valueOf(62));
        }
        return shortUrlBuilder.reverse().toString();
    }

    // 将Base62编码的短链转换回随机ID
    private static BigInteger decode(String shortCode) {
        BigInteger no = BigInteger.ZERO;
        for (char c : shortCode.toCharArray()) {
            int index = BASE62.indexOf(c);
            if (index == -1) throw new IllegalArgumentException("Invalid short URL code");
            no = no.multiply(BigInteger.valueOf(62)).add(BigInteger.valueOf(index));
        }
        return no;
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            String longUrl = "https://www.example.com/a-very-long-url";
            String shortCode = generateShortUrl(longUrl);
            System.out.println("Generated short code: " + shortCode);

            // 测试解析短链
            String resolvedUrl = resolveShortUrl(shortCode);
            System.out.println("Resolved URL: " + resolvedUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
